//
//  WoerterViewController.m
//  Lextra Junior ueb IT
//
//  Created by Dirk Lieder on 27.05.11.
//  Copyright 2011 Phosphon. All rights reserved.
//
#define RGB(r, g, b) \
[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#import "WoerterViewController.h"
#import "Lextra_Engine.h"
#import "NavigationViewController.h"
#import "AsyncImageView.h"
#import "getFilenameHD.h"

//ADDED BY LDHAI
#import "Global.h"

@implementation WoerterViewController

@synthesize myTableView;
//___NGUYEN_HUY_SON__
@synthesize delegate = _delegate;
@synthesize splitViewController;
@synthesize tabBarController;
//___END_NGUYEN_HUY_SON____

//ADDED BY LDHAI
@synthesize labelWoerterView;

static bool DEactiveFlg = false; // active Language

static bool chkAudio = false; // mils rettung...

//_____NGUYEN_HUY_SON_____IPAD_LANDSCAPE_________
- (BOOL)isPadPortrait
{
    
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
            && (self.interfaceOrientation == UIInterfaceOrientationPortrait
                || self.interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown));
}


- (BOOL)isPadLandscape
{
    return (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
            && (self.interfaceOrientation == UIInterfaceOrientationLandscapeRight
                || self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft));
    
}
///______________________________________
static NSMutableArray *listData; // list
static NSMutableArray *listIndex; // indexed list
static NSMutableArray *listIndexArray; // indexed list

//____NGUYEN_HUY_SON__IPAD_ONLY___
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
{
    [myTableView reloadData];
}
//__________END_NGUYEN_HUY_SON__

//_____NGUYEN_HUY_SON_____IPAD_LANDSCAPE_____

//__________________END_NGUYEN_HUY_SON_______
- (void)setDelegate:(id)new_delegate{
	Delegate = new_delegate;
    NavigationViewController *tmp = [Delegate getNavigationID];
    [tmp createNavigationButton:@"IT > DE" callback:self];
}

//change language sort
- (void)nextBarButtonClicked{
    
    //__NGUYEN_HUY_SON
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //Neu iPad
    {
        [listData removeAllObjects];
        [myTableView reloadData];
        
        // Build the array from the plist  
        NSString *path = [[NSBundle mainBundle] pathForResource:@"DBexport" ofType:@"plist"];  
        listData = [[NSMutableArray alloc] initWithContentsOfFile:path];
        
        listIndex = [[NSMutableArray alloc] initWithArray: [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#" componentsSeparatedByString:@"|"]];
        listIndexArray = [[NSMutableArray alloc] init];
        
        NSInteger i;    
        for(i = 0; i<[listIndex count]; i++)
            [listIndexArray addObject:[[NSMutableArray alloc] init]];
        //_________END_NGUYEN_HUY_SON
        DEactiveFlg = !DEactiveFlg;
        // sort Array 
        [listData sortUsingFunction:sort context: nil];
        // create arrays
        [self computeDataArrays];
        [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [myTableView reloadData];//reload data
        [self aktDisplay];
    }
    else
    {

        DEactiveFlg = !DEactiveFlg;

        // sort Array 
        [listData sortUsingFunction:sort context: nil];
        
        // create arrays
        [self computeDataArrays];
        
        
        // Show the string values  
        // for (NSString *str in listData)
        //    NSLog(@"--%@", str);
        
        [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [myTableView reloadData];

        [self aktDisplay];
    }
}

// akt display
- (void)aktDisplay{
    //__NGUYEN_HUY_SON
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) //Neu iPad
    {
        if(DEactiveFlg)
        {
            //self.navigationController.navigationBar.tintColor = [UIColor blueColor]; 
            UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"IT > DE"
                                                                              style:UIBarButtonItemStyleBordered
                                                                             target:self
                                                                             action:@selector(nextBarButtonClicked)];
            [self.navigationController.navigationBar.topItem setRightBarButtonItem:barButtonItem];
            self.navigationItem.rightBarButtonItem = barButtonItem;
            [barButtonItem release];
            
        } 
        else 
        {
            //self.navigationController.navigationBar.tintColor = [UIColor blueColor]; 
            UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"DE > IT"
                                                                              style:UIBarButtonItemStyleBordered
                                                                             target:self
                                                                             action:@selector(nextBarButtonClicked)];
            
            [self.navigationController.navigationBar.topItem setRightBarButtonItem:barButtonItem];
            self.navigationItem.rightBarButtonItem = barButtonItem;
            [barButtonItem release];
            
        }//__END_NGUYEN_HUY_SON
    }
    else
    {
        NavigationViewController *tmp = [Delegate getNavigationID];
        if(DEactiveFlg){
            [tmp createNavigationButton:@"DE > IT" callback:self];
        } else {
            [tmp createNavigationButton:@"IT > DE" callback:self];
        }
    }
    [myTableView reloadData];
}



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //___NGUYEN_HUY_SON__
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        //__NGUYEN_HUY_SON___
       // self.contentSizeForViewInPopover = CGSizeMake(310.0, self.myTableView.rowHeight*2.0);
        //self.navigationController.navigationBar.tintColor = [UIColor blueColor]; 
        
        self.contentSizeForViewInPopover = CGSizeMake(310, self.myTableView.rowHeight*19.0);
        
        UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_table_wort.png"]];
        [self.navigationController.navigationBar addSubview:imageView1];
        [imageView1 release];
        
        self.navigationController.navigationBar.tintColor = [[UIColor alloc] initWithRed:20.0 / 255 green:59.0 / 255 blue:102.0 / 255 alpha:1.0]; 
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"DE > IT"
                                                                          style:UIBarButtonItemStyleBordered
                                                                         target:self
                                                                         action:@selector(nextBarButtonClicked)];
        
        [self.navigationController.navigationBar.topItem setRightBarButtonItem:barButtonItem];
        self.navigationItem.rightBarButtonItem = barButtonItem;
        [barButtonItem release];

        CGFloat navBarHeight = 49.0f;    
        CGRect frame = CGRectMake(self.navigationController.navigationBar.frame.origin.x, self.navigationController.navigationBar.frame.origin.y, self.navigationController.navigationBar.frame.size.width, navBarHeight);
        [self.navigationController.navigationBar setFrame:frame];
        [self.navigationController.navigationBar setBackgroundColor:[[UIColor alloc] initWithRed:134 green:166 blue:228 alpha:1.0]];
        
//        //ADDED BY LDHAI
//        labelWoerterView = [[UILabel alloc] initWithFrame:CGRectMake(900, 10, 100, 30)];
//        labelWoerterView.text = @"Wöster";
//        labelWoerterView.font = [UIFont boldSystemFontOfSize:15.0];
//        labelWoerterView.opaque = NO;
//        labelWoerterView.backgroundColor = [UIColor underPageBackgroundColor];
//        labelWoerterView.textAlignment = UITextAlignmentCenter;
//        labelWoerterView.textColor = [UIColor blackColor];
//        labelWoerterView.layer.cornerRadius = 10.0;
//        labelWoerterView.layer.borderWidth = 1;
//        labelWoerterView.layer.borderColor = [[UIColor blackColor] CGColor];
        
    }  //___END_NGUYEN_HUY_SON
    // Build the array from the plist  
    NSString *path = [[NSBundle mainBundle] pathForResource:@"DBexport" ofType:@"plist"];  
    listData = [[NSMutableArray alloc] initWithContentsOfFile:path];
 
    listIndex = [[NSMutableArray alloc] initWithArray: [@"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z" componentsSeparatedByString:@"|"]];
    listIndexArray = [[NSMutableArray alloc] init];

    
    NSInteger i;    
    for(i = 0; i<[listIndex count]; i++) [listIndexArray addObject:[[NSMutableArray alloc] init]];


    // sort Array 
    [listData sortUsingFunction:sort context: nil];
    
    // create arrays
    [self computeDataArrays];


    // Show the string values  
   // for (NSString *str in listData)
    //    NSLog(@"--%@", str);
    
    [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [myTableView reloadData];
    
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        
        bIsSelectCardView = FALSE;
        NSArray *infoArray = [[listIndexArray objectAtIndex:0] objectAtIndex:0];
        cardController  = [[CardViewController alloc] initWithNibName:@"cardview-iPad" bundle:nil];
        NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, cardController, nil];
        splitViewController.viewControllers = viewControllers;
        
        [cardController setDelegatePlud:self para:infoArray];
        [viewControllers release];
        intDidSelect = 1;

    }
//___END_NGUYEN_HUY_SON_____
  //  [Delegate createNavigationButton:@"DE>IT"];
    
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}


- (NSDictionary*) getPoindInfo:(NSString*)myBild num:(NSInteger)num {
    
    NSDictionary *myLink = nil;
    
    for(int i=0; i<[listData count]; i++) {
        
        NSDictionary *myEintrag = [listData objectAtIndex:i];
        //NSLog(@"--%@--%@--%i", [myEintrag objectForKey:@"wimmelbild"],[myEintrag objectForKey:@"wimmelnummer"],num);

        if([[myEintrag objectForKey:@"wimmelbild"] length]>0 && [[myEintrag objectForKey:@"wimmelnummer"] length]>0){
            if([[myEintrag objectForKey:@"wimmelbild"] isEqualToString:myBild] && [[myEintrag objectForKey:@"wimmelnummer"] isEqualToString:[NSString stringWithFormat:@"%i",num]]) {
                myLink = myEintrag;
            }        
        }
    }
    
    return(myLink);
}

- (NSArray*) getWimmelListPoinds:(NSString*)myBild {
    
    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    
    for(int i=0; i<[listData count]; i++) {
        
        NSDictionary *myEintrag = [listData objectAtIndex:i];
        
        if([[myEintrag objectForKey:@"wimmelbild"] isEqualToString:myBild] && [[myEintrag objectForKey:@"wimmelnummer"] length]>0){
            [myArray addObject:myEintrag];
        }
    }
    
    return(myArray);
}

- (NSMutableArray*) getGameListPoinds{
    
    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    
    for(int i=0; i<[listData count]; i++) {
        
        NSDictionary *myEintrag = [listData objectAtIndex:i];
        
        if([[myEintrag objectForKey:@"spiel"] isEqualToString:@"x"]){
            [myArray addObject:myEintrag];
        }
    }
    
    return(myArray);
}
//______NGUYEN_HUY_SON___IPAD_______SPIELE4_____________
- (NSMutableArray*) getGameListPoinds_IPAD{
    
    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    for(int i=0; i<[listData count]; i++) {
        
        NSDictionary *myEintrag = [listData objectAtIndex:i];
        
        if([[myEintrag objectForKey:@"spiel"] isEqualToString:@"x"]){
            [myArray addObject:myEintrag];
        }
    }
    
    return(myArray);
}

//____END_NGUYEN_HUY_SON
- (NSMutableArray*) getGameListSchnell{
    
    NSMutableArray *myArray = [[NSMutableArray alloc] init];
    
    for(int i=0; i<[listData count]; i++) {
        
        NSDictionary *myEintrag = [listData objectAtIndex:i];
        
        if([[myEintrag objectForKey:@"spielSchnell"] isEqualToString:@"x"]){
            [myArray addObject:myEintrag];
        }
    }
    
    return(myArray);
}



- (void)computeDataArrays {
    
	
	// generate index Array with outputInfo
	NSInteger i,j;
    
	// index array
	for(i=0,j=0; i<[listIndex count]; i++){
		
		// clr old
		[[listIndexArray objectAtIndex:i] removeAllObjects];
		
		// content from index [i]
		for(; j<[listData count];j++){
			
			// get data ptr
			NSDictionary *data;
			data =[listData objectAtIndex:j];
			
			// sort all not matched into last '#'
			BOOL flg = j ==([listData count]-1);
			
			// compare first char (lower or equal for - 
			BOOL firstChar;
            if(DEactiveFlg){
                firstChar = ([[listIndex objectAtIndex:i] caseInsensitiveCompare:[[data objectForKey:@"bezeichnungDE"] substringToIndex:1]] == NSOrderedSame) ||
                ([[listIndex objectAtIndex:i] caseInsensitiveCompare:[[data objectForKey:@"bezeichnungDE"] substringToIndex:1]] == NSOrderedDescending);
            } else {
                firstChar = ([[listIndex objectAtIndex:i] caseInsensitiveCompare:[[data objectForKey:@"bezeichnungFR"] substringToIndex:1]] == NSOrderedSame) ||
                ([[listIndex objectAtIndex:i] caseInsensitiveCompare:[[data objectForKey:@"bezeichnungFR"] substringToIndex:1]] == NSOrderedDescending);
			}
	
			if( firstChar || flg == YES){	
               [[listIndexArray objectAtIndex:i] addObject:data];
            } else break; // next index if not equal
              
            // chk for Audiofile
            if(chkAudio) {
                // ton
                NSString *myFilename,*substring;
                BOOL fileExists;
                NSMutableString *myName = [[NSMutableString alloc] initWithString:[data objectForKey:@"ton"]];
                
                if([myName hasSuffix:@".mp3"]){
                    myFilename = [myName substringToIndex:[myName length]-4];
                } else {
                    myFilename = [[NSString alloc] initWithString:myName];
                }
                
                if(myName){
                    fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[[NSBundle mainBundle] pathForResource:myFilename ofType:@"m4a"]];
                    if(!fileExists)  NSLog(@"--no soundfile-- %@", myFilename );
                    
                }
                // bild
                myName = [[NSMutableString alloc] initWithString:[data objectForKey:@"bild"]];
                if([myName length] > 2){
                    if([myName hasSuffix:@".tif"]){
                        substring = [[NSString alloc] initWithString:[[myName substringToIndex:[myName length]-4] stringByAppendingString:@"_k"]];
                    } else {
                        substring = [[NSString alloc] initWithString:[myName stringByAppendingString:@"_k"]];
                    }
                    fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[PHOSPHON imagePostfix:substring]];
                    if(!fileExists)  NSLog(@"--no bildfile-- %@", myName );
                    
                }
            }
		}
	}
}

- (void)clrDataArrays {
	
	// generate index Array with outputInfo
	NSInteger i;
	
	// index array
	for(i=0; i<[listIndex count]; i++){
		
		// clr old
		[[listIndexArray objectAtIndex:i] removeAllObjects];
	}
}

//  MyOwnClass sort function
int sort( id obj1, id obj2, void *context ){
   // if(DEactiveFlg){
    //    return [[obj1 objectForKey:@"bezeichnungDE"] caseInsensitiveCompare:[obj2 objectForKey:@"bezeichnungDE"]];
   // } else {
   //     return [[obj1 objectForKey:@"bezeichnungFR"] caseInsensitiveCompare:[obj2 objectForKey:@"bezeichnungFR"]];
   // }
    if(DEactiveFlg){
        return [[obj1 objectForKey:@"bezeichnungDE"] localizedCaseInsensitiveCompare:[obj2 objectForKey:@"bezeichnungDE"]];
    } else {
        return [[obj1 objectForKey:@"bezeichnungFR"] localizedCaseInsensitiveCompare:[obj2 objectForKey:@"bezeichnungFR"]];
    }
}



#pragma mark - tableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	//NSUInteger row = [indexPath row];
	
    return 100;			
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //return [listData count];
    return [[listIndexArray objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [listIndexArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	
	NSUInteger row = [indexPath row];
	NSUInteger section = [indexPath section];
	UITableViewCell *cell;
    
	static NSString *CustomCellIdentifier;
    
    // Eintrag
    CustomCellIdentifier = @"part1";
    cell = [tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
    if (cell == nil) {
        // new cell
        cell = [self getCell:CustomCellIdentifier];
    }
    
    UILabel *descriptionLabel = (UILabel*)[cell.contentView viewWithTag:1];
    

    NSMutableString *tmpString1 = [[NSMutableString alloc] initWithString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"artikel"]];
    
    if([tmpString1 length] > 0){
        if(![tmpString1 hasSuffix:@"'"]){
            [tmpString1 appendString:@" "];
        }
    }
    //_____NGUYEN_HUY_SON
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        cell.backgroundColor = [UIColor colorWithRed:172.0/255.0 green:173.0/255.0 blue:175.0/255.0 alpha:1.0];
    }
    //____END_NGUYEN_HUY_SON__
    if([[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"origFR"] length] !=0){
        [tmpString1 appendString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"origFR"]]; 
    } else {
        [tmpString1 appendString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"bezeichnungFR"]]; 
    }

    
    NSMutableString *tmpString2;
    if([[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"origDE"] length] !=0){
        tmpString2 = [[NSMutableString alloc] initWithString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"origDE"]];
    } else {
        tmpString2 = [[NSMutableString alloc] initWithString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"bezeichnungDE"]];
    }
    
    
    if([tmpString2 length] ==0){
        [tmpString2 release];
        tmpString2 = [[NSMutableString alloc] initWithString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"bezeichnungDE"]];
    }
    
    if(DEactiveFlg){
        descriptionLabel.text = tmpString2;
    } else {
        descriptionLabel.text = tmpString1;
    }
    
    descriptionLabel.frame = CGRectMake(100, 18, 195, 50);
    
    CGSize expectedLabelSize = [descriptionLabel.text sizeWithFont:descriptionLabel.font 
                                                 constrainedToSize:descriptionLabel.frame.size
                                                     lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel.frame = CGRectMake(100, 18, 195, expectedLabelSize.height);
    
    
    UILabel *descriptionLabel2 = (UILabel*)[cell.contentView viewWithTag:2];    
    if(DEactiveFlg){
        descriptionLabel2.text = tmpString1;
    } else {
        descriptionLabel2.text = tmpString2;
    }
    descriptionLabel2.frame = CGRectMake(100, 18, 195, 50);
    
    CGSize expectedLabelSize2 = [descriptionLabel2.text sizeWithFont:descriptionLabel2.font 
                                                 constrainedToSize:descriptionLabel2.frame.size
                                                     lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel2.frame = CGRectMake(100, 18, 195, expectedLabelSize2.height);
    descriptionLabel2.center = CGPointMake(descriptionLabel2.center.x, descriptionLabel.bounds.size.height+18 + descriptionLabel2.bounds.size.height/2  );
    
    [tmpString1 release];
    [tmpString2 release];

    
    AsyncImageView *descriptionImage = (AsyncImageView*)[cell.contentView viewWithTag:3];
    NSString *myName = [[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"bild"];

    NSString *substring;
    if([myName length] > 2){
        if([myName hasSuffix:@".tif"]){
            substring = [[NSString alloc] initWithString:[[myName substringToIndex:[myName length]-4] stringByAppendingString:@"_k"]];
        } else {
            substring = [[NSString alloc] initWithString:[myName stringByAppendingString:@"_k"]];
        }
    } else {
        substring = [[NSString alloc] initWithString:@"pirat_k"];
    }
    //NSLog(@"laenge *%@*%d", myName,[myName length]);
    
    [descriptionImage asyncImageLoad:substring];
    [substring release];
    
    
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    return listIndex;
}



#pragma mark -
#pragma mark Table Delegate Methods 


-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath; 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger row = [indexPath row];
	NSUInteger section = [indexPath section];

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        if (splitViewController.pc != nil) 
        {
            [splitViewController.pc dismissPopoverAnimated:YES];
        }
    }
    // show detailcard
    NSArray *infoArray = [[listIndexArray objectAtIndex:section] objectAtIndex:row];
    //___NGUYEN_HUY_SON_
    
    if(intDidSelect == 1)
    {
        [cardController release];
    }
    if(intDidSelect == 2)
    {
        [wimmelView release];
    }
    if([[(NSDictionary*)infoArray objectForKey:@"bild"] length] >0)
    { 
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
        {

            cardController  = [[CardViewController alloc] initWithNibName:@"cardview-iPad" bundle:nil];
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, cardController, nil];
            splitViewController.viewControllers = viewControllers;
            if([self isPadPortrait] == TRUE)
            {
                if (splitViewController.barButton != nil) {
                    [cardController showRootPopoverButtonItem:splitViewController.barButton];
                }
            }
            [cardController setDelegatePlud:self para:infoArray];
            [viewControllers release];
            intDidSelect = 1;
            
            //ADDED BY LDHAI
            //NSLog(@"TABBAR SUBVIEWS: %@",self.tabBarController.tabBar.subviews);
            for(UIView * label in self.tabBarController.tabBar.subviews)
            {
                if([label isMemberOfClass:[UILabel class]])
                    [label removeFromSuperview];
            }
            //NSLog(@"TABBAR SUBVIEWS: %@",self.tabBarController.tabBar.subviews);
            woerterHintStatus = NO;
        }
        else
        {
            [Delegate jmpTo:@"card" name:@"a..c" thePara:infoArray];
        }
    } 
    else 
    {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
        {

            wimmelView =  [[WimmelViewController alloc] initWithNibName:@"wimmelView-iPad" bundle:nil];
            NSArray *viewControllers = [[NSArray alloc] initWithObjects:self.navigationController, wimmelView, nil];
            splitViewController.viewControllers = viewControllers;            
            wimmelView.woerPre = self;
            
            if([self isPadPortrait] == TRUE)
            {
                if (splitViewController.barButton != nil) {
                    [wimmelView showRootPopoverButtonItem:splitViewController.barButton];
                }
            }
            wimmelView.tabbarControllerRoot = tabBarController;
            [wimmelView setDelegatePlud:self para:infoArray bIsParentThemmen:NO];
            [viewControllers release];
            intDidSelect = 2;

            //ADDED BY LDHAI
            if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){

                NSLog(@"PU");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown ){

                NSLog(@"PD");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft ){
//                labelWoerterView = [[UILabel alloc] initWithFrame:CGRectMake(900, 10, 100, 30)];
//                labelWoerterView.text = @"Bild berühren um Menü zu verstecken";
//                labelWoerterView.font = [UIFont boldSystemFontOfSize:15.0];
//                labelWoerterView.opaque = NO;
//                labelWoerterView.backgroundColor = [UIColor underPageBackgroundColor];
//                labelWoerterView.textAlignment = UITextAlignmentCenter;
//                labelWoerterView.textColor = [UIColor blackColor];
//                labelWoerterView.layer.cornerRadius = 10.0;
//                labelWoerterView.layer.borderWidth = 1;
//                labelWoerterView.layer.borderColor = [[UIColor blackColor] CGColor];
//                
//                [self.tabBarController.tabBar addSubview:labelWoerterView];
//                [labelWoerterView release];
                NSLog(@"LL");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight ){
//                labelWoerterView = [[UILabel alloc] initWithFrame:CGRectMake(900, 10, 100, 30)];
//                labelWoerterView.text = @"Bild berühren um Menü zu verstecken";
//                labelWoerterView.font = [UIFont boldSystemFontOfSize:15.0];
//                labelWoerterView.opaque = NO;
//                labelWoerterView.backgroundColor = [UIColor underPageBackgroundColor];
//                labelWoerterView.textAlignment = UITextAlignmentCenter;
//                labelWoerterView.textColor = [UIColor blackColor];
//                labelWoerterView.layer.cornerRadius = 10.0;
//                labelWoerterView.layer.borderWidth = 1;
//                labelWoerterView.layer.borderColor = [[UIColor blackColor] CGColor];
//                
//                [self.tabBarController.tabBar addSubview:labelWoerterView];
//                [labelWoerterView release];
                NSLog(@"LR");
            } 
            woerterHintStatus = YES;
        
        }
        else
        {
            [Delegate jmpTo:@"wimmel" name:@"a..c" thePara:infoArray];//GOi themen
        }
    }
    //__NGUYEN_HUY_SON_END__

    
    /* 
    // first test
    NSString *myFilename;
    NSMutableString *myName = [[NSMutableString alloc] initWithString:[[[listIndexArray objectAtIndex:section] objectAtIndex:row] objectForKey:@"ton"]];
    
    if([myName hasSuffix:@".mp3"]){
        myFilename = [myName substringToIndex:[myName length]-4];
    } else {
        myFilename = [[NSString alloc] initWithString:myName];
    }
    
    NSLog(@"--%@", myFilename);
  
    if(myName){
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:myFilename ofType:@"mp3"]]; 
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        [audioPlayer play];
    }
    
     */
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}



#pragma mark -
#pragma mark cell creation 
-(UITableViewCell*)getCell:(NSString*)myIdentifier{
	
	// new cell
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myIdentifier]autorelease];
	cell.userInteractionEnabled = YES;
    cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Empty.png"]] autorelease];
    cell.selectedBackgroundView.autoresizingMask = UIViewContentModeScaleToFill;
	
	// Text Label blue
	CGRect aframe = CGRectMake(100, 18, 195, 50);
	UILabel *textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0x00, 0x3f, 0x9e);
    textLabel.highlightedTextColor = RGB(0x40, 0x7f, 0xde);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 1;
	//textLabel.frame = CGRectMake(textLabel.frame.origin.x,textLabel.frame.origin.y,320.0,textLabel.frame.size.height);
	[cell.contentView addSubview:textLabel];		

 	// Text Label blak
	aframe = CGRectMake(100, 18, 195, 50);
	textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Italic" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0x00, 0x00, 0x00);
    textLabel.highlightedTextColor = RGB(0x60, 0x60, 0x60);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 2;
	//textLabel.frame = CGRectMake(textLabel.frame.origin.x,textLabel.frame.origin.y,320.0,textLabel.frame.size.height);
	[cell.contentView addSubview:textLabel];		
   
    // image view async
    aframe = CGRectMake(5, 5, 90,90);
    //_________NGUYEN_HUY_SON______
    AsyncImageView *topImageView;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {        
        topImageView = [[AsyncImageView alloc] initWithFrame:aframe];
    }
    else
    {
        topImageView = [[[AsyncImageView alloc] initWithFrame:aframe]autorelease];
    }
    //____END_NGUYEN_HUY_SON___
    topImageView.tag = 3;
    topImageView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    [cell.contentView addSubview:topImageView];	
	
	// trenner
	CGRect frame = CGRectMake(0, 99, 320,1);
	UIImageView *trennerImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"listtrenner.png"]] autorelease];
	trennerImageView.frame = frame;
	[cell.contentView addSubview:trennerImageView];
    
	cell.contentView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    
	return cell;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    //__NGUYEN_HUY_SON__
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        return YES;
    }
    //__NGUYEN_HUY_SON__
    else
    {
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
}
//_______________NGUYEN_HUY_SON__________
- (void)splitViewController:(UISplitViewController*)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem*)barButtonItem forPopoverController:(UIPopoverController*)pc {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        // Keep references to the popover controller and the popover button, and tell the detail view controller to show the button.
        barButtonItem.title = @"Wörter";
        splitViewController.pc = pc;
        splitViewController.barButton = barButtonItem;
        UIViewController <SubstitutableDetailViewController> *detailViewController = [splitViewController.viewControllers objectAtIndex:1];
        [detailViewController showRootPopoverButtonItem:splitViewController.barButton];
        
        //ADDED BY LDHAI
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar1-portrait.png"]];
        
        if([currentViewController isEqualToString:@"Woerter"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar1-portrait.png"]];
        }
        else if ([currentViewController isEqualToString:@"Themen"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar2-portrait.png"]];
        }
        else if ([currentViewController isEqualToString:@"Spiele"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar3-portrait.png"]];
        }
        else
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar4-portrait.png"]];
        }
        
        //UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar1-portrait.png"]];
        [self.tabBarController.tabBar addSubview:imageView];
        [imageView release];
    }
}

- (void)splitViewController:(UISplitViewController*)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem {
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        // Nil out references to the popover controller and the popover button, and tell the detail view controller to hide the button.
        UIViewController <SubstitutableDetailViewController> *detailViewController = [splitViewController.viewControllers objectAtIndex:1];
        [detailViewController invalidateRootPopoverButtonItem:splitViewController.barButton];
        splitViewController.pc = nil;
        splitViewController.barButton = nil;
        
        //ADDED BY LDHAI
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar1.png"]];
        
        if([currentViewController isEqualToString:@"Woerter"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar1.png"]];
        }
        else if ([currentViewController isEqualToString:@"Themen"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar2.png"]];
        }
        else if ([currentViewController isEqualToString:@"Spiele"])
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar3.png"]];
        }
        else
        {
            [imageView setImage:[UIImage imageNamed:@"iPad_tabbar4.png"]];
        }
        
        //UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iPad_tabbar1.png"]];
        [self.tabBarController.tabBar addSubview:imageView];
        [imageView release];
    }
}


//_______END_NGUYEN_HUY_SON____

#pragma mark - VIEW WILL APPEAR
- (void)viewDidDisappear:(BOOL)animated
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        if(woerterHintStatus == YES)
        {
            if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){
                NSLog(@"PU");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown ){
                NSLog(@"PD");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft ){
//                [self.tabBarController.tabBar addSubview:labelWoerterView];
                NSLog(@"LL");
            }
            else if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight ){
//                [self.tabBarController.tabBar addSubview:labelWoerterView];
                NSLog(@"LR");
            }
        }
        else
        {
            for(UIView * label in self.tabBarController.tabBar.subviews)
            {
                if([label isMemberOfClass:[UILabel class]])
                    [label removeFromSuperview];
            }
        }
    }
}

@end
